package com.xingkeduo.config;

import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.pojo.exception.SystemException;
import com.xingkeduo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * <p>
 * 全局异常处理配置
 */

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 全局业务异常
     *
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity errorHandler(Exception ex) {
        log.info("Exception:{}", ex);
        return new ResponseEntity<>(ResponseUtils.error(ex.getMessage(), SystemException.Type.DEFAULT.toString()), HttpStatus.OK);
    }

    @ExceptionHandler(value = InputParamException.class)
    public ResponseEntity handle(InputParamException e) {
        log.info("InputParamException:{}", e);
        return new ResponseEntity<>(ResponseUtils.error(e.getMessage(), e.getCode()), HttpStatus.OK);
    }

    @ExceptionHandler(value = BusinessException.class)
    public ResponseEntity handle(BusinessException e) {
        log.info("BusinessException:{}", e);
        return new ResponseEntity<>(ResponseUtils.error(e.getMessage(), e.getCode()), HttpStatus.OK);
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseEntity handle(MethodArgumentNotValidException e) {
        log.info("MethodArgumentNotValidException:{}", e);
        return new ResponseEntity<>(ResponseUtils.error(e.getBindingResult().getAllErrors().get(0).getDefaultMessage(), SystemException.Type.DEFAULT.toString()), HttpStatus.OK);
    }
}
